const { app, BrowserWindow,ipcMain, session} = require('electron')
const { join } = require('path')
const log= require("electron-log")
const request = require('request');
// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
  });
}
function getRequestId(){
  return guid().replaceAll('-', '').toUpperCase()+'|'+new Date().getTime()
}

function getDataByCookie2Name(cookieStr){
  const cookieStrs = cookieStr.split(';');
  let cookieDatas=[]
  cookieStrs.forEach((cookie)=> {
    let tmpCookies=cookie.replaceAll(' ','').split('=')
    cookieDatas[tmpCookies[0]]=tmpCookies[1]
  });
  return cookieDatas
}
function bytesToString(bytes) {
  let result = ''
  for (let i = 0; i < bytes.length; i++) {
    result += String.fromCharCode(bytes[i])
  }
  return result
}


// 创建浏览器窗口时，调用这个函数。
const createWindow = () => {
    const win = new BrowserWindow({
        width: 1680,
        height: 980,
        webPreferences: {
          preload: join(__dirname, 'preload.js'), // 指定预加载脚本路径
          nodeIntegration: false, // 禁用 Node.js 集成
          contextIsolation: true, // 启用上下文隔离
        },
    })

    // win.loadURL('http://localhost:3000')
    // development模式
    if(process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
        // 开启调试台
        //win.webContents.openDevTools()
    }else {
        win.loadFile(join(__dirname, '../dist/index.html'))
    }
    initFunction(win)
}

// Electron 会在初始化后并准备
app.whenReady().then(() => {
    createWindow()
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

function initFunction(mainWin){
  ipcMain.handle('elemecyShop',async(event,data) => {
    // log.info('elmeLsShop',data)
    const elmecyWin = new BrowserWindow({
      width: 1000,
      height: 600,
      autoHideMenuBar: true,
      parent: mainWin,
      webPreferences: {
        partition: 'partition:'+data.uuid
      }
    })
    elmecyWin.loadURL(data.url)
    elmecyWin.on('close', (event) => {
      session.fromPartition(data.uuid,{cache:false}).clearStorageData();
    });
    let promises=[]
    let result = {tp:data.tp}
    const _url = 'https://app-api.shop.ele.me/xtop/xtop.napos.keeper.permissionManager.getMenuTree/*'
    const ses = elmecyWin.webContents.session
    ses.webRequest.onBeforeSendHeaders({ urls: [_url] }, (details, callback) => {
      ses.cookies.get({ url: 'https://melody.shop.ele.me' }).then((cookies) => {
        let cookieStr=''
        cookies.forEach(function(item){
          cookieStr+=item.name+'='+item.value+';'
        })
        result.cookiestr = cookieStr
      }).catch((error) => {
      })
      callback({ cancel: false, requestHeaders: details.requestHeaders })
    })
    
    promises.push(new Promise(resolve => {
      ses.webRequest.onCompleted({ urls: [_url] }, async(details) => {
        let cookieMap=getDataByCookie2Name(result.cookiestr)
        result.shopId=cookieMap['shopId']
        const shopParam = JSON.stringify({
          "metas": {
              "shopId": cookieMap['shopId'],
              "ksid": cookieMap['ksid'],
              "loginRestaurantId": cookieMap['shopId']
          },
          "params": {
              "param": {
                  "shopId": cookieMap['shopId']
              }
          }
        })
        const respon = await elmecyWin.webContents.executeJavaScript(`
          fetch('https://httpizza.ele.me/xtop/xtop.shop.shopBusinessQueryTop.queryShopStatusViewDetail/1.0', {
            method: 'post',
            body: '${shopParam}',
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(resp => resp.json())
       `)
        console.log('eleme respon',respon)
        let module=respon.result.module
        let shopInfo=module.shopInfoVO
        result.shopName=shopInfo.shopName
        result.shopLogo=shopInfo.logoUrl
        result.shopStatus=module.shopStatusView.showMainStatus.statusRemark
        resolve('')
      })
    }))
    await Promise.all(promises)
    return result
  })
    
  ipcMain.handle('jdcyShop',async(event,data) => {
    // log.info('elmeLsShop',data)
    const jdcyWin = new BrowserWindow({
        width: 1000,
        height: 600,
        autoHideMenuBar: true,
        parent: mainWin,
        webPreferences: {
        partition: 'partition:'+data.uuid
        }
    })

    jdcyWin.loadURL(data.url)
    jdcyWin.on('close', (event) => {
      session.fromPartition(data.uuid,{cache:false}).clearStorageData();
    });
    const _url = 'https://sff.jddj.com/api?v=1.0&appId=YNE4XWZFDHXOYGKZU5FN&api=dsm.o2o.order.home.getData'
    let promises=[]
    let result = {tp:data.tp,shopId:'-1',shopName:'-1'}
    const ses = jdcyWin.webContents.session
    promises.push(
      new Promise((resolve) => {
        ses.webRequest.onCompleted({ urls: [_url] }, (details) => {
          ses.cookies.get({ url: 'https://store.jddj.com' }).then((cookies) => {
              let cookieStr=''
              cookies.forEach(function(item){
              cookieStr+=item.name+'='+item.value+';'
              })
              result.cookiestr = cookieStr
              resolve('')
          }).catch((error) => {
          })
        })
      })
    )
    await Promise.all(promises)
    return result
  })
  ipcMain.handle('mtShop',async (event,data)=>{
    const mtWin = new BrowserWindow({
        width: 900,
        height: 600,
        autoHideMenuBar: true,
        parent: mainWin,
        webPreferences: {
        partition: 'partition:'+data.uuid
        }
    })
    const ses = mtWin.webContents.session
    
    mtWin.loadURL(data.url)

    mtWin.on('close', (event) => {
      session.fromPartition(data.uuid).clearStorageData();
    });
    let promises=[]
    let result = {tp:data.tp}
    let tmpUrls=[]
    ses.webRequest.onBeforeSendHeaders({ urls: ['https://*/api/poi/*', "https://*/v2/sc/index/r/poiInfo/get*", "https://*/api/v2/account/homePage*"] }, (details, callback) => {
      result.cookiestr = details.requestHeaders.Cookie
      callback({ cancel: false, requestHeaders: details.requestHeaders })
    })
    promises.push(new Promise(resolve => {
      ses.webRequest.onCompleted({urls: ["https://*/api/*", "https://*/v2/*"]}, async (details) => {
        if (details.url.indexOf('account/homePage') > -1 && Object.keys(tmpUrls).indexOf('account/homePage') === -1) {
          const resp = await details.webContents.executeJavaScript(`fetch('${details.url}').then(resp=>resp.json())`);
          result.shopName = resp.data.wmPoiName;
          result.shopStatus = resp.data.wmPoiStatusDesc;
          let cookieDatas=getDataByCookie2Name(result.cookiestr)
          result.shopId=cookieDatas['wmPoiId']
          result.spId=cookieDatas['acctId']
          result.remark=resp.data.acctName
          result.shopCategory=cookieDatas['shopCategory']
          tmpUrls['account/homePage'] = true;
        }
        if (details.url.indexOf('index/homePage') > -1 && Object.keys(tmpUrls).indexOf('index/homePage') === -1) {
          const resp = await details.webContents.executeJavaScript(`fetch('${details.url}').then(resp=>resp.json())`);
          result.shopLogo = resp.data.wmPoiData.logoUrl;
          if(!result.shopLogo.startsWith('http')){
            result.shopLogo='https:'+result.shopLogo
          }
          tmpUrls['index/homePage'] = true;
        }

        if (details.url.includes("sc/index/r/poiInfo/get") && Object.keys(tmpUrls).includes("sc/index/r/poiInfo/get")===-1) {
          const resp = await details.webContents.executeJavaScript(`fetch('${details.url}').then(resp=>resp.json())`);
          result.shopLogo = resp.data.wmPoiData.logoUrl;
          if(!result.shopLogo.startsWith('http')){
            result.shopLogo='https:'+result.shopLogo
          }
          result.shopName = resp.data.wmPoiData.wmPoiName;
          result.remark = resp.data.userName;
          result.shopId = resp.data.wmPoiId;
          tmpUrls["sc/index/r/poiInfo/get"] = true;
          tmpUrls["poi/poiList"] = true;
        }
        console.log(Object.keys(tmpUrls))
        if (Object.keys(tmpUrls).length >= 2) {
          resolve('');
        }
      })
    }))
    await Promise.all(promises);
    console.log('result',result)
    return result;
  })

  ipcMain.on('openShop',(event,data) => {
    const shopWin = new BrowserWindow({
      width: 1200,
      height: 800,
      autoHideMenuBar: true,
      webPreferences: {
        partition: 'persist:'+data.shopId
      }
    })
    const ses = shopWin.webContents.session
    const cookieStrs = data.cookie.split(';');
    cookieStrs.forEach(function(cookie) {
      const tmpCookies=cookie.replaceAll(' ','').split('=')
      if(tmpCookies[0].length>0){
        ses.cookies.set({url:data.url,name:tmpCookies[0],value:tmpCookies.length>1?tmpCookies[1]:"",domain: data.domain})
      }
    });
    if(data.url.indexOf('melody.shop.ele.me')>-1){
      shopWin.loadURL('https://melody.shop.ele.me/app/shop/'+data.shopId+'/dashboard#app.shop.dashboard')
    }else{
      shopWin.loadURL(data.url)
    }
  })
  
  ipcMain.handle('elemecypost',async (event,data) => {
    let cookieMap=getDataByCookie2Name(data.cookiestr)
    let shopId=cookieMap['shopId']
    let ksid=cookieMap['ksid']
    
    let bodyData={
      "service": "FoodService2",
      "method": "queryCategoryWithFoodFilter",
      "params": {
          "request": {
              "shopId": shopId,
              "foodQueryFilter": "ALL",
              "withFoods": true
          }
      },
      "id": getRequestId(),
      "metas": {
          "appVersion": "1.0.0",
          "appName": "melody",
          "ksid": ksid,
          "shopId": shopId
      },
      "ncp": "2.0.0"
    }
    let options = {
      'method': 'POST',
      'url': 'https://app-api.shop.ele.me/nevermore.goods/invoke/?method=FoodService2.queryCategoryWithFoodFilter',
      'headers': {
          'authority': 'app-api.shop.ele.me',
          'accept': 'application/json, text/plain, */*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'origin': 'https://melody.shop.ele.me',
          'referer': 'https://melody.shop.ele.me/app/shop/'+shopId+'/food',
          'sec-ch-ua': '"Not;A=Brand";v="99", "Chromium";v="106"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-site',
          'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HAODATA/6.0.30 Chrome/106.0.5249.199 Electron/21.4.4 Safari/537.36',
          'x-eleme-requestid': bodyData.id,
          'x-shard': 'shopid='+shopId,
          'content-type': 'application/json;charset=UTF-8',
          'Host': 'app-api.shop.ele.me',
          'Connection': 'keep-alive'
      },
      body: JSON.stringify(bodyData)
    }

    let sbodyData={
      "id": getRequestId(),
      "method": "queryFoodsByGroupGlobalId",
      "service": "FoodService2",
      "params": {
          "request": {
              "shopId": shopId,
              "groupGlobalId": "",
              "withPackageUpgradeTag": true
          }
      },
      "metas": {
          "appName": "melody",
          "appVersion": "4.4.0",
          "ksid": ksid,
          "shopId": shopId
      },
      "ncp": "2.0.0",
      "adapter": "ncp",
      "extendConfig": {
          "docMode": "master,,"
      }
    }
    let soptions = {
      'method': 'POST',
      'url': 'https://app-api.shop.ele.me/nevermore.goods/invoke?method=FoodService2.queryFoodsByGroupGlobalId',
      'headers': {
        'authority': 'app-api.shop.ele.me',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN',
        'origin': 'https://napos-goods-pc.faas.ele.me',
        'referer': 'https://napos-goods-pc.faas.ele.me/',
        'sec-ch-ua': '"Not;A=Brand";v="99", "Chromium";v="106"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HAODATA/6.0.30 Chrome/106.0.5249.199 Electron/21.4.4 Safari/537.36',
        'x-shard': 'shopid='+shopId,
        'Cookie': data.cookiestr,
        'content-type': 'application/json;charset=UTF-8',
        'Host': 'app-api.shop.ele.me',
        'Connection': 'keep-alive'
      },
      body:""
    };
    let tbodyData={
      "id": getRequestId(),
      "method": "getFoodDetail",
      "service": "FoodService2",
      "params": {
          "request": {
              "itemGlobalId": "",
              "shopId": shopId
          }
      },
      "metas": {
          "appName": "melody",
          "appVersion": "4.4.0",
          "ksid": ksid,
          "shopId": shopId
      },
      "ncp": "2.0.0",
      "adapter": "ncp"
    }
    let toptions = {
      'method': 'POST',
      'url': 'https://app-api.shop.ele.me/nevermore.goods/invoke/?method=FoodService2.getFoodDetail',
      'headers': {
          'authority': 'app-api.shop.ele.me',
          'accept': 'application/json, text/plain, */*',
          'accept-language': 'zh-CN',
          'origin': 'https://napos-goods-pc.faas.ele.me',
          'referer': 'https://napos-goods-pc.faas.ele.me/',
          'sec-ch-ua': '"Not;A=Brand";v="99", "Chromium";v="106"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-site',
          'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HAODATA/6.0.30 Chrome/106.0.5249.199 Electron/21.4.4 Safari/537.36',
          'x-shard': 'shopid='+shopId,
          'Cookie': data.cookiestr,
          'content-type': 'application/json;charset=UTF-8',
          'Host': 'app-api.shop.ele.me',
          'Connection': 'keep-alive'
      },
      body: ''
    }
    let responDataStr =await requestPromise(options)
    let responData=JSON.parse(responDataStr)
    let shopTags=[]
    let shopItems=[]
    let newShopTags=[]
    let newShopItems=[]
    let waitGetData=[]
    if(responData!==undefined&&responData!==null&&(responData.ret===undefined||responData.ret===null)){
      if(responData.result!==undefined&&responData.result!==null&&responData.result.length>0){
        shopTags=responData.result
        newShopTags=shopTags.map((tag,index)=>{
          let foodList=tag.foodList
          if(foodList!==undefined&&foodList!==null&&foodList.length>0){
            shopItems=shopItems.concat(foodList)
          }else{
            waitGetData.push(tag.groupGlobalId)
          }
          return {
            tagId:tag.groupGlobalId,
            tagName:tag.name,
            productCount:tag.foodCount,
            seq:index
          }
        })
        if(waitGetData.length>0){
          for(let i=0;i<waitGetData.length;i++){
            sbodyData.params.request.groupGlobalId=waitGetData[i]
            sbodyData.id=getRequestId()
            soptions.body=JSON.stringify(sbodyData)
            let sresponDataStr =await requestPromise(soptions)
            let sresponData=JSON.parse(sresponDataStr)
            if(sresponData.result!==undefined&&sresponData.result!==null&&sresponData.result.foods!==undefined&&sresponData.result.foods!==null&&sresponData.result.foods.length>0){
              shopItems=shopItems.concat(sresponData.result.foods)
            }
          }
        }
      }
      if(shopItems.length>0){
        for(let j=0;j<shopItems.length;j++){
          let item=shopItems[j]
          let skus=item.specs.map(sku=>{
            return {
              price:sku.price,
              spec:sku.name,
              stock:sku.stock,
              weight:'1',
              weightUnit:'人份',
              unit:'1人份',
              id:sku.id,
              boxNum:sku.packageShare,
              boxPrice:sku.packageFee,
              actPrice:sku.activityPrice===undefined||sku.activityPrice===null?0.0:sku.activityPrice
            }
          })
          let newItem={
            id:item.itemGlobalId,
            tp:'eleme',
            name:item.name,
            categoryId:item.category299Id,
            tagId:item.groupGlobalId,
            picture:item.imageUrl,
            attrs:[],
            skus:skus,
            ddbs:JSON.stringify(item.simpleFoodTags).indexOf('单点不送')>-1?1:0,//1 点不送
            sellStatus:item.onShelf?0:1,
            description:''
          }
          try{
            tbodyData.params.request.itemGlobalId=item.itemGlobalId
            tbodyData.id=getRequestId()
            toptions.body=JSON.stringify(tbodyData)
            let detailStr=await requestPromise(toptions)
            //console.log('detail',toptions,detailStr)
            let detail=JSON.parse(detailStr).result
            newItem.description=detail.description
            newItem.attrs=detail.properties
            detail.specs.forEach(sku=>{
              for(let z=0;z<skus.length;z++){
                if(skus[z].id===sku.id){
                  let specAttribute=sku.specAttribute
                  skus[z].weight=specAttribute.weight
                  skus[z].weightUnit=specAttribute.unit
                  skus[z].unit=specAttribute.weight+specAttribute.unit
                  break
                }
              }
            })
            if(detail.ingredientGroups!==undefined&&detail.ingredientGroups!==null&&detail.ingredientGroups.length>0){
              let topGroup= detail.ingredientGroups.map(top=>{
                let detailTop=[]
                for(let x=0;x<top.ingredientSkuList.length;x++){
                  let dt=top.ingredientSkuList[x]
                  detailTop.push({
                    name:dt.itemName,
                    price:dt.price,
                    seq:x
                  })
                }
                return {
                  name:top.name,
                  tops:detailTop
                }
              })
              newItem.topGroup=topGroup
            }
          }catch(error){
            //
          }
          newItem.skus=skus
          newShopItems.push(newItem)
        }
      }
    }else{
      return {errorMsg:'获取数据失败，请重试！'+responDataStr}
    }
   // console.log('shopTags',newShopTags)
   // console.log('shopItems',newShopItems)
    return {shopTags:newShopTags,shopItems:newShopItems}
  })
  ipcMain.handle('mtcypost',async (event,data) => {
    let cookieMap=getDataByCookie2Name(data.cookiestr)
    let wmPoiId=cookieMap['wmPoiId']
    let postCookie='region_id='+cookieMap['region_id']+';region_version='+cookieMap['region_version']+';a3='+cookieMap['WEBDFPID'].split('-')[0]
    let url='https://waimaieapp.meituan.com/gw/bizproduct/v3/food/r/spuListV2?'
    let options = {
      'method': 'POST',
      'url': 'https://waimaieapp.meituan.com/gw/bizproduct/v3/food/r/spuListV2?'+data.urlParamStr,
      'headers': {
         'Accept': '*/*',
         'Accept-Language': 'zh-CN,zh;q=0.9,ko;q=0.8',
         'Connection': 'keep-alive',
         'Origin': 'https://waimaie.meituan.com',
         'Referer': 'https://waimaie.meituan.com/',
         'Sec-Fetch-Dest': 'empty',
         'Sec-Fetch-Mode': 'cors',
         'Sec-Fetch-Site': 'same-origin',
         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
         'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
         'sec-ch-ua-mobile': '?0',
         'sec-ch-ua-platform': '"Windows"',
         'Cookie': data.cookiestr, 
         'content-type': 'application/x-www-form-urlencoded',
         'Host': 'waimaieapp.meituan.com'
      },
      form: {
      'opType': 0,
      'queryCount': 0,
      'pageNum': 1,
      'pageSize': 30,
      'wmPoiId': wmPoiId,
      'needAllCount': false,
      'needTagList': true,
      'scenario': '0'
      }
    }

    let cwoptions = {
      'method': 'POST',
      'url': data.apiurl+'/shop/requestUrlParam',
      'headers': {
         'Authorization': 'Bearer '+data.token,
         'Content-Type': 'application/json'
      },
      body: ''
    }
    
    let shopTags=[]
    let shopItems=[]
    let totalCount=0;
    let i=1
    let scount=-1
    while(scount<totalCount){
      cwoptions.body = JSON.stringify({'cookiestr': postCookie,'pageNum': i})
      let cwresponDataStr=await requestPromise(cwoptions)
      options.url=url+JSON.parse(cwresponDataStr).data
      options.form.pageNum = i
      let responDataStr=await requestPromise(options)
      let responData=JSON.parse(responDataStr)
      if(responData!==undefined&&responData!==null&&responData.code===0){
        totalCount=responData.data.totalCount
        if(responData.data.tagList!==undefined&&responData.data.tagList!==null&&responData.data.tagList.length>0){
          shopTags=responData.data.tagList
        }
        if(responData.data.productList!==undefined&&responData.data.productList!==null&&responData.data.productList.length>0){
          shopItems=shopItems.concat(responData.data.productList)
        }
      }
      options.form.pageNum=++i
      options.form.needTagList=false
      scount=shopItems.length
    }

    let newShopTags=shopTags.map(tag=>{
      return {
        tagId:tag.id,
        tagName:tag.name,
        productCount:tag.productCount,
        seq:tag.sequence
      }
    })
    let newShopItems=shopItems.map(item=>{
      let attrList=item.attrList.map(attr=>{
        return {
          id:attr.id,
          mode:attr.mode,
          value:attr.value,
          name:attr.name,
          seq:attr.no,
          price:attr.price
        }
      })
      let actPrice=0.0
      let skus=item.wmProductSkus.map(sku=>{
        let actInfoList=sku.actInfoList
        if(actInfoList!==undefined&&actInfoList!==null&&actInfoList.length>0){
          actPrice=actInfoList[0].actShowPrice
        }
        return {
          price:sku.price,
          spec:sku.spec,
          stock:sku.stock,
          weight:sku.weight,
          weightUnit:sku.weightUnit,
          unit:sku.unit,
          id:sku.id,
          boxNum:sku.boxNum,
          boxPrice:sku.boxPrice,
          skuAttrs:sku.skuAttrList,
          actPrice:actPrice
        }
      })
      return {
        tp:'mtcy',
        id:item.id,
        name:item.name,
        categoryId:item.categoryId,
        tagId:item.tagId,
        picture:item.shownPicture,
        description:item.description,
        attrs:attrList,
        skus:skus,
        ddbs:item.singleOrderNoDelivery,//1 点不送
        sellStatus:item.sellStatus
      }
    })
    return {shopTags:newShopTags,shopItems:newShopItems}
  })
}

function requestPromise (options) {
  options.timeout = 30000
  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) {
        log.error('远程请求错误',options,error)
        reject(error);
      }else{
        resolve(body);
      }
    })
  })
}
